package com.kaibes.module.theme;

import static com.kaibes.web.response.ResponseFactory.deleteFailure;
import static com.kaibes.web.response.ResponseFactory.deleteSuccess;
import static com.kaibes.web.response.ResponseFactory.postFailure;
import static com.kaibes.web.response.ResponseFactory.postSuccess;
import static com.kaibes.web.response.ResponseFactory.putFailure;
import static com.kaibes.web.response.ResponseFactory.putSuccess;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.base.annotation.Description;
import com.kaibes.core.base.util.FileUtils;
import com.kaibes.core.base.util.ZipUtils;
import com.kaibes.web.api.ApiLink;
import com.kaibes.web.api.ResponseApi;
import com.kaibes.web.prefix.PrefixContext;

@RestController
@RequestMapping("/themes")
public class ThemeApi extends ResponseApi<Theme, ThemeService> {

    @Autowired
    private PrefixContext prefixContext;
    @Autowired
    private ObjectMapper objectMapper;

    @PutMapping("/turn/{path}")
    @ApiLink("启用或禁用主题")
    public ResponseEntity<Object> turn(@PathVariable @Description("主题路径") String path) {
        Theme theme = service.getByPath(path);
        if (theme.isEnable()) {
            Theme temp = service.getByUriButNotPath(theme.getUri(), theme.getPath());
            if (temp != null) {
                temp.setEnable(true);
                prefixContext.changePrefixTarget(theme.getUri(), temp.getPath());
                service.updateByPath(temp);
            } else {
                return putFailure("不能禁用唯一的主题，否则网站会因为缺少主题而崩溃！");
            }
            theme.setEnable(false);
            service.updateByPath(theme);
            return putSuccess("禁用主题成功！");
        } else {
            Theme temp = service.getByActiveTrue(theme.getUri());
            if (temp != null) {
                temp.setEnable(false);
                service.updateByPath(temp);
            }
            prefixContext.changePrefixTarget(theme.getUri(), theme.getPath());
            theme.setEnable(true);
            service.updateByPath(theme);
            return putSuccess("启用主题成功！");
        }
    }

    @DeleteMapping("/{path}")
    @ApiLink("删除主题")
    public ResponseEntity<Object> delete(@PathVariable @Description("主题路径") String path) {
        Theme theme = service.getByPath(path);
        if (theme == null) {
            return deleteFailure("主题已经不存在！");
        }
        Theme temp = service.getByUriButNotPath(theme.getUri(), theme.getPath());
        if (temp == null) {
            return deleteFailure("不能删除唯一的主题，否则网站会因为缺少主题而崩溃！");
        }
        if (service.removeByPath(path)) {
            FileUtils.delete(new File(ThemeConfig.THEME_DIR, path));
            return deleteSuccess("删除主题成功");
        } else {
            return deleteFailure("删除主题失败");
        }
    }

    @ApiLink("上传主题，文件参数是“file”")
    @PostMapping("/upload")
    public ResponseEntity<Object> uploadTheme(HttpServletRequest request,
            @RequestParam("file") @Description("主题文件包") MultipartFile file) {
        if (file.isEmpty()) {
            return postFailure("上传失败，请选择文件");
        }

        try {
            if (!ZipUtils.hasRootDir(file.getInputStream())) {
                return postFailure("主题包最底层必须是文件夹！");
            }

            String root = ZipUtils.getRootDir(file.getInputStream());
            File temp = new File(ThemeConfig.THEME_DIR, root);
            if (temp.exists()) {
                return postFailure("主题文件夹已存在，请更换主题文件夹！");
            }

            if (!ZipUtils.hasFile(file.getInputStream(), "theme.json")) {
                return postFailure("不是合法的主题zip包！");
            }

            ZipUtils.unZipFile(file.getInputStream(), ThemeConfig.THEME_DIR);

            FileInputStream fis = new FileInputStream(ThemeConfig.THEME_DIR + root + "theme.json");
            JsonNode json = objectMapper.readTree(fis);
            fis.close();

            String uri = json.get("uri").textValue();
            Theme theme = new Theme();
            theme.setPath(root.substring(0, root.length() - 1));
            theme.setUri(uri);
            theme.setEnable(false);

            if (service.save(theme) != null) {
                return postSuccess("上传主题成功");
            } else {
                return postFailure("上传主题失败！");
            }
        } catch (IOException e) {
            return postFailure("上传主题失败！");
        }

    }

}
